package Java7_Concurrency_Cookbook.concurrent_custom.custom_fork_join_worker_thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
 * <b>通过实现ThreadFactory接口为Fork/Join框架生成定制线程</b><br/>
 * ForkJoinPool能够执行两种类型的任务: RecursiveTask, RecursiveAction.<br/>
 * ForkJoinPool并不直接执行任务(RecursiveTask, RecursiveAction),
 * 而是通过ForkJoinWorkerThreadFactory创建的ForkJoinWorkerThread来执行任务.<br/>
 * <br/>
 * 本示例中, ForkJoinPool使用MyWorkerThreadFactory产生的MyWorkerThread来执行任务<br/>
 * @author lixiangke
 * @date 2017/11/27
 */
public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // factory 用于产生工作者线程, 工作者线程用于执行MyRecursiveTask
        MyWorkerThreadFactory factory = new MyWorkerThreadFactory();
        ForkJoinPool pool = new ForkJoinPool(4, factory, null, false);
        int[] array = new int[10000];
        for (int i = 0; i < array.length; i++) {
            array[i] = 1;
        }
        MyRecursiveTask task = new MyRecursiveTask(array, 0, array.length);
        pool.execute(task);
        task.join();

        //TimeUnit.SECONDS.sleep(10);
        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.DAYS);
        System.out.printf("Main: Result: %d\n", task.get());
        System.out.printf("Main: End Of the Program.\n");
    }
}
